<template>
	<!-- 员工搬离 -->
	<a-modal :visible="visible" width="1000px" title="搬离" centered destroyOnClose :maskClosable="false" @cancel="cancel" :footer="null" :bodyStyle="{padding: 0}">
		<a-form ref="formRef" :model="modelRef" :rules="formRules" layout="horizontal" class="flex-container-nomal" :labelCol="{style: {width: '90px'}}" style="height: 70vh" @finish="submit">
			<div class="flex1 auto-y">
				<a-space :size="12" direction="vertical" style="width: 100%">
					<div class="d-module-title">
						<b>房间信息</b>
					</div>
					<a-row :gutter="10">
						<a-col>
							<a-form-item label="房源地址" name="houseAddress">
								<a-input v-model:value="modelRef.houseAddress" disabled placeholder="请输入房源地址" />
							</a-form-item>
						</a-col>
						<a-col>
							<a-form-item label="搬离日期" name="quiteDate" :rules="[{required: true, message: '请选择搬离日期'}]">
								<a-date-picker v-model:value="modelRef.quiteDate" :value-format="DATE_FORMAT.DATE" :disabled="modelRef.normal === 1 || contractDetail.contractStatus == 23" :disabled-date="disabledDate" @change="incomeList()" />
							</a-form-item>
						</a-col>
						<a-col>
							<a-button type="primary" @click="addClick" style="width: 160px">
								<check-outlined v-if="JSON.stringify(delivery.info) != '{}'" />
								<plus-outlined v-else />
								确认退房交割单
							</a-button>
							<span class="margin-left-10" v-if="JSON.stringify(delivery.info) == '{}'" v-color="{color: 'danger'}">请先处理物业交割单，再完成搬离</span>
						</a-col>
					</a-row>

					<div class="d-module-title">
						<b>结算明细</b>
					</div>
					<vxe-table :data="tableData" ref="tableRef" :footer-span-method="footerColspanMethod" :footer-method="footerMethod" stripe align="center" :row-config="{isHover: true, height: 80}" show-footer>
						<vxe-column title="收支类型" field="feeDirection" width="100" align="left" footer-align="left">
							<template #footer>
								<div class="flex-space-between">
									<span>费用总计：{{ totalMoney }}元</span>
									<div>
										<a class="processing" @click="addTogether(1)" style="margin-right: 20px">
											<plus-square-outlined />
											添加收款项
										</a>
										<a class="error" @click="addTogether(2)">
											<minus-square-outlined />
											添加付款项
										</a>
									</div>
								</div>
							</template>
							<template #default="{row}">
								<svg-icon :icon-class="`finance-${row.feeDirection == 1 ? 'in' : 'out'}`" style="width: 22px; height: 14px; margin-right: 6px" />
								<span :class="(row.feeDirection == 1 ? 'processing' : 'error') + '-color'">{{ row.feeDirection == 1 ? '收' : '支' }}</span>
							</template>
						</vxe-column>
						<vxe-column title="费用科目" field="feeSubjectId" min-width="120">
							<template #default="{row}">
								<a-select v-model:value="row.feeSubjectId" :class="{error: !row.feeSubjectId}" :disabled="row.disabled" :options="feeSubject" show-search option-filter-prop="name" :field-names="{label: 'name', value: 'id', options: 'metaList'}" placeholder="请选择费用科目" style="width: 100%; text-align: left" />
							</template>
						</vxe-column>
						<vxe-column title="费用承担方" field="feeSubjectId" min-width="100">
							<template #default="{row}">
								<!-- {{ costSide[(costSideList||[]).map(o=>o.feeSubjectId === row.feeSubjectId)[0]?.type||2] }} -->
								<!-- {{ costSideList.filter(o=>o.feeSubjectId === row.feeSubjectId) }} -->
								{{ returnCostSide(row.feeSubjectId) }}
							</template>
						</vxe-column>
						<vxe-column title="金额(元)" field="amount" width="150">
							<template #default="{row}">
								<a-input-number v-model:value="row.amount" :class="{error: row.amount === null || row.amount < 0}" :min="0" :precision="2" placeholder="请输入金额" style="width: 100%" />
							</template>
						</vxe-column>
						<vxe-column title="账单周期" field="cycle" min-width="180">
							<template #default="{row}">
								<a-range-picker :class="{error: !row.timeInfo.length}" style="width: 100%" v-model:value="row.timeInfo" :value-format="DATE_FORMAT.DATE" />
							</template>
						</vxe-column>
						<vxe-column title="操作" field="action" width="100">
							<template #default="{row, rowIndex}">
								<a-button type="link" size="small" danger @click="tableData.splice(rowIndex, 1)">删除</a-button>
							</template>
						</vxe-column>
					</vxe-table>

					<div class="d-module-title">
						<b>备注</b>
					</div>
					<a-form-item label="" name="quiteComment">
						<a-textarea v-model:value="modelRef.quiteComment" placeholder="请输入备注" :rows="4" show-count :maxlength="200" />
					</a-form-item>
				</a-space>
			</div>
			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-button @click="cancel">取消</a-button>
					<a-button :loading="loading" :disabled="loading" type="primary" html-type="submit">确定</a-button>
				</a-space>
			</div>
		</a-form>
		<device-tip v-model:visible="deviceTipVisible" :accessShow="accessShow" :lockShow="lockShow" @success="handleOk"></device-tip>
		<lease-off-settlement v-model:visible="deliveryVisible" :id="employeeDetail.contractId" :houseId="employeeDetail.renterInfoId" :type="2" @success="getDelivery"></lease-off-settlement>
	</a-modal>
</template>
<script setup lang="ts">
	import {computed, reactive, ref, watch} from 'vue'
	import {cabcelBreakAbnormalList, charterCheckOutHouse, getRenterContractDetail, renterContractDeviceDetail,  deviceStatus, employeeCheckinDetails, enterBreakList} from '@/api/contract'
	import {MinusSquareOutlined, PlusOutlined, PlusSquareOutlined, CheckOutlined} from '@ant-design/icons-vue'
	import dayjs, {Dayjs} from 'dayjs'
	import {useRequest} from 'vue-request'
	import {message, Modal} from 'ant-design-vue'
	import LeaseOffSettlement from '@/components/contract/tenant/lease-off-settlements.vue'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {RenterContract} from '@/interface/contract'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import DeviceTip from '@/components/contract/tenant/device-tip.vue'
	import {VxeTablePropTypes} from 'vxe-table'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import {getDispose} from '@/api/charter-contract'
	import {isD3B} from 'yuxin-base/src/utils/device'

	const props = defineProps<{
		id: string | number
		visible: boolean
		applyId?: [string, number]
	}>()

	const deliveryVisible = ref<boolean>(false)
	const deviceTipVisible = ref<boolean>(false)
	// const houseId = ref<boolean>(false)
	const modelRef = reactive({
		quiteDate: '',
		quiteComment: '',
		houseId: '',
		// 只作展示用的字段
		houseAddress: '',
		normal: 0,

		paymentAccountType: 1,
		paymentAccount: ''
	})
	const formRules = {}

	const feeSubject = ref<any>([])

	const disabledDate = (current: Dayjs) => {
		// 非合同即将搬入状态只能选择合同开始日期到当天日期
		return dayjs(current).format('YYYY-MM-DD') < dayjs(contractDetail.value.beginTime).format('YYYY-MM-DD') || dayjs(current).format('YYYY-MM-DD') > dayjs(contractDetail.value.endTime).format('YYYY-MM-DD')
		// return current && current.isAfter(dayjs().add(1, 'day'), 'day')
	}

	const addClick = () => {
		deliveryVisible.value = true
		console.log(modelRef.houseId, 'modelRef.houseIdmodelRef.houseId')
	}

	const contractDetail = ref<RenterContract>({})

	const getData = () => {
		// 获取租客详情
		getRenterContractDetail(employeeDetail.value.contractId).then(({data}) => {
			contractDetail.value = data
			modelRef.houseAddress = data.house.address
			modelRef.houseId = data.houseId
			let date = new Date()
			let beginTime = new Date(data.createTime)
			let quiteDate = ''
			if (date.getTime() < beginTime.getTime()) {
				quiteDate = dayjs(beginTime).format(DATE_FORMAT.DATE)
			} else {
				quiteDate = nowDate()
			}
			modelRef.quiteDate = quiteDate
			if (data.contractStatus == 26) {
				modelRef.normal = 1
				modelRef.quiteDate = data.endTime
			}
			getEnterBreakList()
		})
		// 获取费用科目列表
		settingApi.getDicListByLabel(DIC_LABEL_MAP.FEESUBJECT).then(({data}) => {
			data.forEach((item: any) => {
				item.selectable = false
			})
			feeSubject.value = data
		})
	}
	const getEnterBreakList = () => {
		let params = {
			contractId: employeeDetail.value.contractId,
			quiteDate: modelRef.quiteDate
		}
		enterBreakList(params).then(({data}) => {
			billList(data)
		})
	}
	const lockShow = ref<boolean>(false)
	const accessShow = ref<boolean>(false)
	//获取门禁门锁是否离线
	const getDeviceInformation = () => {
		let params = {
			id: employeeDetail.value.contractId,
			renterId: contractDetail.value?.renterInfo?.id || ''
		}
		renterContractDeviceDetail(params.id,params.renterId).then((res: any) => {
			let data = res.data
			if (data?.hasLock && !data.lockOnline) {
				lockShow.value = true
			}
			if (data?.hasAccess && !data.accessOnline) {
				accessShow.value = true
			}
			if (accessShow.value || lockShow.value) {
				deviceTipVisible.value = true
			} else {
				message.success('操作成功')
				emit('success')
				cancel()
			}
		})
	}
	const handleOk = () => {
		deviceTipVisible.value = false
		emit('success')
		cancel()
	}
	const baseNumbe = ref<any>({})
	const incomeList = async (data: any = []) => {
		const params = {
			contractId: employeeDetail.value.contractId,
			quiteDate: modelRef.quiteDate,
			meterReadRecordDtos: data
		}
		const res: any = await enterBreakList(params)
		if (res.code == 200) {
			res.data.forEach((item: any) => {
				item.disabled = true
				item.timeInfo = [item.beginDate, item.endDate]
				// 表单校验
				item.checkFeeSubjectId = true
				item.checkAmount = true
				item.checkTimeInfo = true
			})
			tableData.value = res.data
		}
	}
	const billList = async (data: any = []) => {
		data.forEach((item: any) => {
			item.disabled = true
			item.timeInfo = [item.beginDate, item.endDate]
			// 表单校验
			item.checkFeeSubjectId = true
			item.checkAmount = true
			item.checkTimeInfo = true
			let index = tableData.value.findIndex(o => o.id === item.id)
			if (index === -1) {
				tableData.value.push(item)
			} else {
				tableData.value[index] = {...item}
			}
		})
		tableRef.value?.reloadData(tableData.value)
	}

	const totalMoney = computed(() => {
		let total = 0
		for (let item of tableData.value) {
			if (item.feeDirection === 1) {
				total += item.amount * 1
			} else {
				total -= item.amount * 1
			}
		}
		return total.toFixed(2)
	})
	//费用承担方相关
	const costSideList = reactive<any>([])
	const costSide = reactive<any>({
		1: '企业',
		2: '个人',
		3: '混合'
	})
	const getDisposeInfo = () => {
		getDispose(enterPriseContractId.value).then(res => {
			console.log(res.data)
			costSideList.value = res.data
		})
	}
	const returnCostSide = feeSubjectId => {
		return costSide[costSideList.value.filter(o => o.feeSubjectId === feeSubjectId)[0]?.type || 2]
	}
	// table ---------------------------------------------------------------------------------------------------------
	const footerColspanMethod: VxeTablePropTypes.FooterSpanMethod = ({$rowIndex, _columnIndex}) => {
		if ($rowIndex === 0) {
			if (_columnIndex === 0) {
				return {
					rowspan: 1,
					colspan: 5
				}
			}
		}
	}
	const footerMethod: VxeTablePropTypes.FooterMethod = ({columns, data}) => {
		return [columns.map(() => null)]
	}

	const columns = [
		{
			title: '收支类型',
			dataIndex: 'feeDirection',
			width: 100,
			align: 'center'
		},
		{
			title: '费用科目',
			dataIndex: 'feeSubjectId',
			width: 200,
			align: 'center'
		},
		{
			title: '金额(元)',
			dataIndex: 'amount',
			width: 150,
			align: 'center'
		},
		{
			title: '账单周期',
			key: 'cycle',
			align: 'center'
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 100
		}
	]

	const tableData = ref<any>([])
	const tableRef = ref<any>(null)

	const addTogether = (type: number | string) => {
		let obj = {
			// 收支金额
			amount: '',
			timeInfo: [],
			beginDate: '',
			// 费用类型
			costType: 0,
			endDate: '',
			// 费用方向【1收入2支出】
			feeDirection: type,
			// 费用科目id【字典】
			feeSubjectId: null,
			// 费用科目名称
			feeSubjectName: '',
			// 表单校验
			checkFeeSubjectId: true,
			checkAmount: true,
			checkTimeInfo: true
		}
		tableData.value.push(obj)

		tableRef.value?.reloadData(tableData.value)
	}
	const lockInfo = ref<any>({})
	watch(
		() => props.visible,
		async (newVal: boolean) => {
			if (newVal && props.id) {
				getEmployeeCheckinDetails()
				if (isLockinEnv()) {
					const {data = {}} = await deviceStatus(props.id)
					lockInfo.value = data
				}
			} else {
				baseNumbe.value = {}
			}
		}
	)
	const employeeDetail = ref<any>({})
	const enterPriseContractId = ref('')
	const getEmployeeCheckinDetails = () => {
		employeeCheckinDetails(props.id).then(res => {
			employeeDetail.value = res.data
			modelRef.houseAddress = res.data.houseAddress
			enterPriseContractId.value = res.data.enterPriseContractId
			getData()
			getDisposeInfo()
		})
	}
	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		delivery.info = {}
		emit('update:visible', false)
		resetForm()
	}

	const delivery = reactive<any>({
		info: {}
	})
	const getDelivery = (data: any) => {
		delivery.info = data
		// 设备费用存在 刷新账单
		if (delivery.info?.meterReadRecordDtos && delivery.info.meterReadRecordDtos.length) {
			incomeList(delivery.info.meterReadRecordDtos)
		}

		// 能源预警
		if (delivery.info?.earlyData && delivery.info.earlyData.length) {
			billList(delivery.info.earlyData)
		}
		// 能源预警
		if (delivery.info?.energyDictArr && delivery.info.energyDictArr.length) {
			billList(delivery.info.energyDictArr)
		}
	}

	const submit = () => {
		if (JSON.stringify(delivery.info) != '{}') {
			if (modelRef.normal === 1 && dayjs().isBefore(modelRef.quiteDate, 'day')) {
				return message.error('合同未到期，无法办理到期退')
			}

			// isBindEnergyDevice 是否绑定能耗设备 0.是 1.否
			if (contractDetail.value.isBindEnergyDevice === 0 && JSON.stringify(delivery.info) === '{}') {
				if (!isLockinEnv()) return message.error('请在交割单输入能耗读数')
			}

			let checkFee = false
			for (let item of tableData.value) {
				item.checkFeeSubjectId = !item.feeSubjectId ? false : true
				if (!item.feeSubjectId) {
					checkFee = true
				}
				item.checkAmount = !(item.amount * 1 >= 0) ? false : true
				if (!(item.amount * 1 >= 0)) {
					checkFee = true
				}
				if (item.timeInfo.length == 0) {
					item.checkTimeInfo = false
					checkFee = true
				} else {
					item.beginDate = item.timeInfo[0]
					item.endDate = item.timeInfo[1]
					item.checkTimeInfo = true
				}
			}
			if (checkFee) {
				return
			}
			if (isLockinEnv()) {
				handleOfflineLock()
			}
			run()
		} else {
			return message.error('请确认退租交割单')
		}
	}

	const sendRequest = () => {
		//物业交割单
		let newDelivery = JSON.parse(JSON.stringify(delivery.info))
		// 根据付费类型 不同的数组
		let meters = newDelivery.meters
		let type = newDelivery.billGenerateMethod
		if (type === 2 || type === 3) {
			meters = newDelivery[type === 2 ? 'meterReadRecordDtos' : 'energyDictArr'].map((e: any) => {
				return {
					deviceType: e.deviceType,
					deviceId: e.deviceId,
					read: type === 2 ? e.amount : e.lastRead
				}
			})
			newDelivery.meters = meters
			delete newDelivery['meterReadRecordDtos']
			delete newDelivery['energyDictArr']
		}
		const params: any = {
			enterEmployeeId: props.id,
			enterPriseContractId: employeeDetail.value.enterPriseContractId,
			compactId: employeeDetail.value.contractId,
			houseId: modelRef.houseId,
			finances: tableData.value,
			quiteComment: modelRef.quiteComment,
			checkInEndTime: modelRef.quiteDate,
			deliveryType: 2,
			compactType: 2,
			...newDelivery
		}
		return charterCheckOutHouse(params)
	}

	const {run, loading} = useRequest(sendRequest, {
		manual: true,
		formatResult: (res: any) => {
			getDeviceInformation()
			// message.success('操作成功')
			// emit('success')
			// cancel()
		}
	})
	const handleOfflineLock = () => {
		const {hasLock, sn} = lockInfo.value || {}
		if (hasLock && isD3B(sn)) {
			Modal.warning({
				title: '提醒',
				icon: null,
				content: '请使用管家端锁前连接蓝牙后删除门锁授权。或设备详情中获取删除码门前按键输入删除码后删除。'
			})
		}
	}

	// 重置表单
	const formRef = ref<any>()
	const resetForm = () => {
		modelRef.houseId = ''
		modelRef.paymentAccountType = 1
		tableData.value = []
		delivery.info = {}
		formRef.value.resetFields()
	}
</script>

<style lang="less" scoped>
	:deep(.vxe-table--footer-wrapper.body--wrapper) {
		overflow: hidden;
	}
	.margin-left-10 {
		margin-left: 10px;
	}
</style>
